package com.talkweb.platform.commonapi.utils;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class BeanHolder implements ApplicationContextAware
{
    
    private static ApplicationContext applicationContext = null;
    
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException
    {
        if (BeanHolder.applicationContext == null)
        {
            BeanHolder.applicationContext = applicationContext;
        }
    }
    
    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext()
    {
        
        return applicationContext;
        
    }
    
    /**
     * 通过name获取 Bean
     */
    public static Object getBean(String name)
    {
        
        return null == applicationContext ? null : applicationContext.getBean(name);
        
    }
    
    /**
     * 通过class获取Bean
     */
    public static <T> T getBean(Class<T> clazz)
    {
        
        return null == applicationContext ? null : applicationContext.getBean(clazz);
        
    }
    
    /**
     * 通过name,以及Clazz返回指定的Bean
     */
    public static <T> T getBean(String name, Class<T> clazz)
    {
        
        return null == applicationContext ? null : applicationContext.getBean(name, clazz);
        
    }
    
    /**
     * 返回该类型的所有实现类
     * 
     * @param <E> 泛型
     * @param clazz 类型
     * @return 返回IOC容器中所有该类型实例对象
     */
    public static <E> Map<String, E> getBeans(Class<E> clazz)
    {
        return null == applicationContext ? null : applicationContext.getBeansOfType(clazz);
    }
    
}